import sys
from pathlib import Path
import tkinter as tk
from tkinter import ttk, messagebox
import plotly.express as px
import pandas as pd
import numpy as np
import asyncio
import threading
from typing import Dict, List
import requests

# 添加项目根目录到PATH
sys.path.append(str(Path(__file__).parent))
from agents.job_agent_system import JobAgentSystem

class JobRecommendationApp:
    def __init__(self, root):
        self.root = root
        self.root.title("智能岗位推荐系统")
        
        # 初始化多智能体系统
        self.agent_system = JobAgentSystem()
        
        # API基础URL
        self.api_url = "http://localhost:8000"
        
        # 创建UI
        self.create_widgets()
        
        # 加载初始数据
        self.load_initial_data()
    
    def create_widgets(self):
        """创建用户界面组件"""
        # 主框架
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 输入区域
        input_frame = ttk.LabelFrame(main_frame, text="个人信息", padding="10")
        input_frame.grid(row=0, column=0, sticky=(tk.W, tk.E))
        
        # 技能输入
        ttk.Label(input_frame, text="技能 (空格分隔):").grid(row=0, column=0, sticky=tk.W)
        self.skills_entry = ttk.Entry(input_frame, width=50)
        self.skills_entry.grid(row=0, column=1, padx=5, pady=5)
        
        # 经验输入
        ttk.Label(input_frame, text="工作经验 (年):").grid(row=1, column=0, sticky=tk.W)
        self.experience_entry = ttk.Entry(input_frame, width=10)
        self.experience_entry.grid(row=1, column=1, padx=5, pady=5, sticky=tk.W)
        
        # 行业输入
        ttk.Label(input_frame, text="目标行业:").grid(row=2, column=0, sticky=tk.W)
        self.industry_combobox = ttk.Combobox(
            input_frame, 
            values=["IT", "Finance", "Healthcare", "Education", "Manufacturing"],
            width=15
        )
        self.industry_combobox.grid(row=2, column=1, padx=5, pady=5, sticky=tk.W)
        self.industry_combobox.current(0)
        
        # 分析深度
        ttk.Label(input_frame, text="分析深度:").grid(row=3, column=0, sticky=tk.W)
        self.analysis_depth = tk.IntVar(value=1)
        ttk.Radiobutton(input_frame, text="基础", variable=self.analysis_depth, value=1).grid(row=3, column=1, sticky=tk.W)
        ttk.Radiobutton(input_frame, text="高级", variable=self.analysis_depth, value=2).grid(row=3, column=2, sticky=tk.W)
        
        # 按钮区域
        button_frame = ttk.Frame(main_frame)
        button_frame.grid(row=1, column=0, pady=10)
        
        ttk.Button(
            button_frame, 
            text="分析匹配", 
            command=self.on_analyze
        ).grid(row=0, column=0, padx=5)
        
        ttk.Button(
            button_frame, 
            text="行业趋势", 
            command=self.on_trend_analysis
        ).grid(row=0, column=1, padx=5)
        
        ttk.Button(
            button_frame, 
            text="退出", 
            command=self.root.quit
        ).grid(row=0, column=2, padx=5)
        
        # 结果区域
        self.result_text = tk.Text(
            main_frame, 
            width=80, 
            height=20, 
            wrap=tk.WORD
        )
        self.result_text.grid(row=2, column=0, pady=10)
        
        # 状态栏
        self.status_var = tk.StringVar()
        self.status_var.set("就绪")
        ttk.Label(
            main_frame, 
            textvariable=self.status_var,
            relief=tk.SUNKEN
        ).grid(row=3, column=0, sticky=(tk.W, tk.E))
    
    def load_initial_data(self):
        """加载初始数据"""
        try:
            response = requests.get(f"{self.api_url}/skills")
            if response.status_code == 200:
                data = response.json()
                if data["success"]:
                    self.skills_entry.insert(0, " ".join(data["data"][:5]))  # 添加示例技能
        except Exception as e:
            self.log_error(f"初始化数据加载失败: {str(e)}")
    
    def on_analyze(self):
        """分析按钮回调"""
        # 在后台线程中运行分析
        threading.Thread(
            target=self.run_analysis,
            daemon=True
        ).start()
    
    def on_trend_analysis(self):
        """行业趋势分析按钮回调"""
        industry = self.industry_combobox.get()
        threading.Thread(
            target=self.run_trend_analysis,
            args=(industry,),
            daemon=True
        ).start()
    
    def run_analysis(self):
        """执行分析任务"""
        self.set_status("分析中...")
        
        try:
            # 获取用户输入
            user_skills = self.skills_entry.get().split()
            experience = int(self.experience_entry.get())
            industry = self.industry_combobox.get()
            
            # 调用API进行匹配分析
            response = requests.post(
                f"{self.api_url}/match",
                json={
                    "user_skills": user_skills,
                    "job_skills": ["Python", "SQL", "Machine Learning"]  # 示例岗位技能
                }
            )
            
            if response.status_code == 200:
                data = response.json()
                if data["success"]:
                    self.show_result(
                        f"技能匹配分析结果:\n"
                        f"匹配分数: {data['match_score']:.2f}\n"
                        f"建议: {self.get_recommendation(data['match_score'])}"
                    )
            
            # 高级分析
            if self.analysis_depth.get() == 2:
                self.run_advanced_analysis(user_skills, industry)
            
            self.set_status("分析完成")
        except Exception as e:
            self.log_error(f"分析过程中出错: {str(e)}")
            self.set_status("分析失败")
    
    def run_advanced_analysis(self, skills: List[str], industry: str):
        """执行高级分析"""
        try:
            # 调用多智能体系统进行行业趋势分析
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            
            trend = loop.run_until_complete(
                self.agent_system.analyze_industry_trends(industry)
            )
            
            self.show_result(
                f"\n\n行业趋势分析 ({industry}):\n"
                f"{trend['analysis']}\n"
                f"新兴技能: {', '.join(trend['emerging_skills'])}"
            )
            
            loop.close()
        except Exception as e:
            self.log_error(f"高级分析失败: {str(e)}")
    
    def run_trend_analysis(self, industry: str):
        """执行行业趋势分析"""
        self.set_status(f"分析{industry}行业趋势...")
        
        try:
            # 调用API进行趋势分析
            response = requests.post(
                f"{self.api_url}/analyze",
                json={"industry": industry, "years": 5}
            )
            
            if response.status_code == 200:
                data = response.json()
                if data["success"]:
                    self.show_result(
                        f"{industry}行业趋势分析:\n"
                        f"{data['data']['analysis']}\n"
                        f"建议关注技能: {', '.join(data['data']['emerging_skills'])}"
                    )
            
            self.set_status("趋势分析完成")
        except Exception as e:
            self.log_error(f"趋势分析失败: {str(e)}")
            self.set_status("趋势分析失败")
    
    def get_recommendation(self, score: float) -> str:
        """根据匹配分数获取建议"""
        if score >= 0.8:
            return "高度匹配 - 强烈建议申请相关岗位"
        elif score >= 0.6:
            return "中等匹配 - 建议补充1-2项关键技能"
        else:
            return "匹配度低 - 建议系统学习相关技能"
    
    def show_result(self, text: str):
        """显示结果到UI"""
        self.root.after(0, lambda: self.result_text.insert(tk.END, text + "\n\n"))
    
    def log_error(self, message: str):
        """记录错误信息"""
        self.root.after(0, lambda: self.result_text.insert(
            tk.END, f"错误: {message}\n\n"
        ))
    
    def set_status(self, message: str):
        """更新状态栏"""
        self.root.after(0, lambda: self.status_var.set(message))

def main():
    root = tk.Tk()
    app = JobRecommendationApp(root)
    root.mainloop()

if __name__ == "__main__":
    main()